<!--点餐部分-->
<template>
  <div class="pos">
    <el-row>
      <!-- 订单部分 -->
      <el-col :span="10" id="order-list" class="pos-left">
        <el-affix :offset="20">
          <el-tabs v-model="activeName" class="post-tab" stretch="true" @tab-click="handleClick">
            <el-tab-pane label="点餐" name="first">
              <div class="order-meal">
                <div class="tableItem">
                  <el-table
                      :data="displayedItems"
                      fit="true"
                  >
                    <el-table-column prop="name" label="商品" align="center"></el-table-column>
                    <el-table-column label="数量" align="center">
                      <template #default="scope">
                        <div v-if="option!==scope.$index">
                          {{ displayedItems[scope.$index].num }}
                        </div>
                        <el-input-number v-model="displayedItems[scope.$index].num"
                                         :min="1" :max="20" size="small"
                                         :style="{width: '80px'}"
                                         v-if="option===scope.$index"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="温度" align="center">
                      <template #default="scope">
                        <div v-if="option!==scope.$index">
                          {{ iceList[displayedItems[scope.$index].ice].label }}
                        </div>
                        <el-select v-model="displayedItems[scope.$index].ice" class="m-2" placeholder="Select"
                                   size="small" v-if="option==scope.$index">
                          <el-option
                              v-for="item in iceList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="糖度" align="center">
                      <template #default="scope">
                        <div v-if="option!==scope.$index">
                          {{ sugarList[displayedItems[scope.$index].sugar].label }}
                        </div>
                        <el-select v-model="displayedItems[scope.$index].sugar" class="m-2" placeholder="Select"
                                   size="small" v-if="option==scope.$index">
                          <el-option
                              v-for="item in sugarList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="price" label="单价" align="center"></el-table-column>
                    <el-table-column label="操作" fixed="right" align="center" width="100px">
                      <template #default="scope">
                        <el-button type="text" @click="handleUpdate(scope.$index, scope.row)"
                                   v-if="option!==scope.$index">编辑
                        </el-button>
                        <el-button type="text" @click="handleOK(scope.$index, scope.row)" v-if="option===scope.$index">
                          确定
                        </el-button>
                        <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                      </template>

                    </el-table-column>
                  </el-table>
                  <el-pagination
                      background
                      :current-page="currentPage"
                      :page-size="pageSize"
                      :total="total"
                      layout="prev, pager, next"
                      @current-change="handleCurrentChange"
                  />
                </div>
                <div class="order-total">
                  <p><span>总数量：</span><span>{{ totalCount }}</span></p>
                  <p><span>总金额：</span><span>{{ totalMoney }} 元</span></p>
                </div>
                <div class="order-buttons">
                  <el-button type="success" size="large" @click="checkout()" style="width: 60px">结账</el-button>
                  <el-button type="primary" size="large" @click="handup()" style="width: 60px">挂单</el-button>
                  <el-button type="warning" size="large" @click="remove()" style="width: 60px">删除</el-button>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="挂单" name="second">
              <div class="order-handup">
                <orderHandUp @my-event="showMsg"/>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-affix>
      </el-col>
      <!-- 商品部分 -->
      <el-col :span="14" class="pos-right">
        <!-- top部分 -->
        <!--        <pos-often></pos-often>-->
        <!-- 商品种类部分 -->
        <div class="goods-type">
          <el-tabs class="type-tabs">
            <el-tab-pane label="咖啡">
              <ul class="cookList">
                <li v-for="item in coffers" @click="add_to_orderList(item)">
                  <div class="left-Img">
                    <img :src="'src/assets/cofferimg/'+item.image" width="100%"/>
                  </div>
                  <div class="right-text">
                    <span class="foodName">{{ item.name }}</span>
                    <span class="foodPrice">￥{{ item.price }}元</span>
                  </div>
                </li>
              </ul>
            </el-tab-pane>

            <el-tab-pane label="茶饮">
              <ul class="cookList">
                <li v-for="item in teas" @click="add_to_orderList(item)">
                  <div class="left-Img">
                    <img :src="'src/assets/cofferimg/'+item.image" width="100%"/>
                  </div>
                  <div class="right-text">
                    <span class="foodName">{{ item.name }}</span>
                    <span class="foodPrice">￥{{ item.price }}元</span>
                  </div>
                </li>
              </ul>
            </el-tab-pane>

            <el-tab-pane label="甜点">
              <ul class="cookList">
                <li v-for="item in cakes" @click="add_to_orderList(item)">
                  <div class="left-Img">
                    <img :src="'src/assets/cofferimg/'+item.image" width="100%"/>
                  </div>
                  <div class="right-text">
                    <span class="foodName">{{ item.name }}</span>
                    <span class="foodPrice">￥{{ item.price }}元</span>
                  </div>
                </li>
              </ul>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import axios from "axios";
import orderHandUp from "./OrderHandUp.vue"
//左边
const activeName = ref('first')
const iceList = [
  {label: "常温", value: 0},
  {label: "冰", value: 1},
  {label: "热", value: 2}
]
const sugarList = [
  {label: "正常", value: 0},
  {label: "七分", value: 1},
  {label: "五分", value: 2},
  {label: "三分", value: 3},
  {label: "无糖", value: 4}
]
let totalCount: number = 0
let totalMoney: number = 0
let goods_table_data = ref([{
  productid: 0,
  name: "string",
  price: 0,
  num: 0,
  ice: 0,
  sugar: 0,
  sid: 123456
}])
// let goods = ref(goods_table_data)
//右边
const coffers = ref([])
const cakes = ref([])
const teas = ref([])

let option = -1

// 在组件挂载后执行回调函数
onMounted(() => {
  if (totalCount == 0) remove()
  getData()
})

//获取当前页数据
const getData = () => {
  axios.get('http://192.168.166.182:8080/product/getAll', {})
      .then(res => {
        console.log(res.data)
        // coffers.value = res.data;
        coffers.value = res.data.filter(item => {
          return item.categoryid === 1
        })
        teas.value = res.data.filter(item => {
          return item.categoryid === 2
        })
        cakes.value = res.data.filter(item => {
          return item.categoryid === 3
        })
      })
      .catch(error => {
        console.error(error);
      });
};

//
function showMsg(data) {
  goods_table_data.value = data
  total = ref(goods_table_data.value.length)
  calTotal()
  handleCurrentChange(1)
}

const add_to_orderList = (item) => {
  // alert(item.price)
  goods_table_data.value.push({
    productid: item.productid,
    name: item.name,
    price: item.price,
    num: 1,
    ice: 0,
    sugar: 0,
    sid: null
  })
  total = ref(goods_table_data.value.length)
  totalMoney = totalMoney + parseFloat(item.price)
  // alert(item.price)
  // alert(total)
  alert("确认添加到订单")
  totalCount = totalCount + 1;
  handleCurrentChange(1);
}

// 删除订单中的某一条
const handleDelete = (index, row) => {
  totalCount = totalCount - parseInt(row.num);
  totalMoney = totalMoney - (parseInt(row.num) * parseFloat(row.price))
  goods_table_data.value.splice(index, 1)
  total = ref(goods_table_data.value.length)
  handleCurrentChange(1)
}

// 分页
let currentPage = 1;// 定义当前页码初始值为1
const pageSize = 3;// 定义每页显示的数据条数为5
let total = ref(goods_table_data.value.length);// 初始化数据总条数
let displayedItems = ref(goods_table_data.value.slice(0, pageSize));//初始化当前页显示数据

function handleCurrentChange(newPage) {
  currentPage = newPage
  const startIndex = (newPage - 1) * pageSize
  displayedItems.value = goods_table_data.value.slice(startIndex, startIndex + pageSize)
}

//结账
const checkout = () => {
  let ddbh = 123;
  axios.put(`http://192.168.166.182:8080/orderForm/addOrder`, goods_table_data.value, {
        params: {
          totalnum: totalCount,
          total: totalMoney,
          remarks: "",
          cid:0
        }
      }
  )
      .then(response => {
        // 处理成功响应
        console.log(response)
        window.open(`http://192.168.166.182:8080/alipay/pay?traceNo=${response.data}&totalAmount=${totalMoney}`,)
        goods_table_data.value = []
        calTotal()
        handleCurrentChange(1)
        alert('付款成功!')
      })
      .catch(error => {
        // 处理错误
        console.error('添加失败');
        console.error(error);
      });

}

//挂单按钮
const handup = () => {
  alert("确定挂单？")
  const oo = goods_table_data.value

  // axios.post('http://192.168.166.182:8080/gd/add')
  axios.post('http://192.168.166.182:8080/gd/add', oo)
      .then(response => {// 处理成功响应
        alert("挂单成功")
        goods_table_data.value.splice(0, goods_table_data.value.length)
        totalCount = 0
        totalMoney = 0
        handleCurrentChange(1)
      })
      .catch(error => {// 处理错误
        console.log(error);
      });
}

//删除按钮
const remove = () => {
  goods_table_data.value.splice(0, goods_table_data.value.length)
  calTotal()
  handleCurrentChange(1)
}

//计算总金额、总数
const calTotal = () => {
  totalMoney = 0
  totalCount = 0
  for (let i = 0; i < goods_table_data.value.length; i++) {
    console.log(goods_table_data.value[i].num)
    totalCount = totalCount + goods_table_data.value[i].num;
    totalMoney = totalMoney + goods_table_data.value[i].price * goods_table_data.value[i].num
  }
}

const handleUpdate = (index, row) => {
  option = index
  console.log(option)
  console.log(index)
  console.log(option !== index)
  handleCurrentChange(currentPage)
}

const handleOK = (index, row) => {
  let xiabiao = (currentPage - 1) * pageSize + index;
  goods_table_data.value[xiabiao].ice = row.ice;
  goods_table_data.value[xiabiao].sugar = row.sugar;
  goods_table_data.value[xiabiao].num = row.num
  calTotal()
  handleCurrentChange(1)
  option = -1
}

const handleClick = () => {
  // console.log(tab)
  if (activeName.value === 'first') {
    onMounted(null)
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  /*background-color: #646cff;*/
}

.pos {
  height: 100vh;
}

.pos-left {
  height: 100%;
  background-color: #fff;
}

.pos-right {
  height: 100vh;
}

/*左边*/
.post-tab {
  /*background-color: #888888;*/
  --el-tabs-header-height: 65px;
}

.post-tab p {
  width: 33.333%;
  text-align: center;
  font-size: 1rem;
}

.order-total {
  margin-top: 1.5rem;
  display: flex;
  flex-direction: row;
  justify-content: center;
  font-size: 1rem;
}

.order-total p {
  margin-right: 2rem;
}

.order-total p :last-child {
  font-weight: 600;
  font-size: 1rem;
  color: #337ecc;
}

.el-pagination { /*选择分页组件，默认采取Flex布局*/
  justify-content: center; /*水平方向居中对齐*/
  margin-top: 8px;
}

.tableItem {
  height: 300px;
}

.order-buttons {
  display: flex;
  justify-content: center;
  padding: 40px;
}


/*右边*/
.goods-type /deep/ .el-tabs__item {
  font-size: 16px;
}

.goods-type {
  /*margin-top: 40px;*/
  padding: 0 10px;
  box-sizing: border-box;
  background-color: #ecf5ff;
  height: 100%;
  --el-transfer-panel-body-height: 100%;
}

.cookList {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.cookList li {
  width: 30%;
  list-style: none;
  border: 1px solid #e5e9f2;
  overflow: hidden;
  background-color: #fff;
  margin: 1%;
  border-radius: 5px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.cookList li :hover {
  transform: scale(1.05);
}

.cookList li .left-Img {
  width: 40%;
  height: 100%;
}

.cookList li .left-Img img {
  display: inline-block;
  width: 100%;
  height: 100%;
}

.cookList li .right-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.cookList li .foodName {
  font-size: 1rem;
  padding: 1rem;
  box-sizing: border-box;
  font-weight: 600;
  color: #337ecc;
}

.cookList li .foodPrice {
  font-size: 1rem;
  padding: 10px;
  box-sizing: border-box;
}

.type-tabs {
  padding-top: 40px;
}

</style>
